package com.patrol.logisticsmanage.ui.canteen;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.github.florent37.viewanimator.ViewAnimator;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.patrol.logisticsmanage.R;
import com.patrol.logisticsmanage.net.AppConfig;
import com.patrol.logisticsmanage.net.BaseObserver;
import com.patrol.logisticsmanage.net.BaseReponse;
import com.patrol.logisticsmanage.net.BaseRequest;
import com.patrol.logisticsmanage.ui.base.BaseActivity;
import com.patrol.logisticsmanage.ui.canteen.Views.AddWidget;
import com.patrol.logisticsmanage.ui.canteen.Views.MaxHeightRecyclerView;
import com.patrol.logisticsmanage.ui.canteen.Views.ShopCarView;
import com.patrol.logisticsmanage.ui.canteen.Views.ShopInfoContainer;
import com.patrol.logisticsmanage.ui.canteen.adapters.CarAdapter;
import com.patrol.logisticsmanage.ui.canteen.bean.FoodBean;
import com.patrol.logisticsmanage.ui.canteen.bean.RequestFoodListBean;
import com.patrol.logisticsmanage.ui.canteen.bean.Restaurant;
import com.patrol.logisticsmanage.ui.canteen.behaviors.AppBarBehavior;
import com.patrol.logisticsmanage.ui.canteen.fragments.FirstFragment;
import com.patrol.logisticsmanage.ui.canteen.fragments.SecondFragment;
import com.patrol.logisticsmanage.ui.canteen.utils.GsonUtil;
import com.patrol.logisticsmanage.ui.canteen.utils.LogUtils;
import com.patrol.logisticsmanage.ui.canteen.utils.ToastUtils;
import com.patrol.logisticsmanage.ui.canteen.utils.ViewUtils;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.slidebar.ScrollBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@Route(path = "/app/canteenDetail")
public class CanteenDetailActivity extends BaseActivity implements AddWidget.OnAddClick {
    public static final String CAR_ACTION = "handleCar";
    public static final String CLEARCAR_ACTION = "clearCar";
    @BindView(R.id.collapsing_toolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.ll_cut)
    LinearLayout llCut;
    @BindView(R.id.shopcontainer)
    ShopInfoContainer shopInfoContainer;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.indicator)
    ScrollIndicatorView indicator;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.scroll_container)
    LinearLayout scrollContainer;
    @BindView(R.id.blackview)
    View blackview;
    @BindView(R.id.car_recyclerview)
    MaxHeightRecyclerView carRecyclerview;
    @BindView(R.id.car_container)
    LinearLayout carContainer;
    @BindView(R.id.car_nonselect)
    TextView carNonselect;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.amount_container)
    LinearLayout amountContainer;
    @BindView(R.id.car_limit)
    TextView carLimit;
    @BindView(R.id.car_rl)
    RelativeLayout carRl;
    @BindView(R.id.iv_shop_car)
    ImageView ivShopCar;
    @BindView(R.id.car_badge)
    TextView carBadge;
    @BindView(R.id.car_mainfl)
    ShopCarView shopCarView;
    @BindView(R.id.rootview)
    CoordinatorLayout rootview;
    public BottomSheetBehavior behavior;
    public View scroll_container;
    private FirstFragment firstFragment;
    public static CarAdapter carAdapter;
    @Autowired
    String restaurantString;
    Restaurant restaurant;
    @Autowired
    boolean isCanOrder;

    List<RequestFoodListBean> requestFoodListBeanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canteen_detail);
        ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initViews();
        IntentFilter intentFilter = new IntentFilter(CAR_ACTION);
        intentFilter.addAction(CLEARCAR_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);

        requestFoodListBeanList = new ArrayList<>();
        restaurant = GsonUtil.gsonToBean(restaurantString,Restaurant.class);
        shopInfoContainer.shop_name.setText(restaurant.getName());
        Glide.with(mContext)
                .load(restaurant.getPicture())
                .centerCrop()
                .placeholder(R.drawable.icon_shop)
                .into(shopInfoContainer.iv_shop);
//        Glide.with(mContext)
//                .load(restaurant.getPicture())
//                .centerCrop()
//                .placeholder(R.drawable.icon_shop)
//                .into(shopInfoContainer.iv_shop_bg);
        ViewUtils.getBlurFresco(mContext, shopInfoContainer.iv_shop_bg, restaurant.getPicture());
        getFoodList();
        if (isCanOrder){
            shopCarView.setVisibility(View.VISIBLE);
        }else {
            shopCarView.setVisibility(View.GONE);
        }
    }

    private void getFoodList() {
        BaseRequest.getInstance().getApiServise().getFoodList(restaurant.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<RequestFoodListBean>>(this) {
                    @Override
                    public void onSuccess(BaseReponse<List<RequestFoodListBean>> baseReponse) {
                        List<RequestFoodListBean> list = baseReponse.getResults();
//                        List<RequestFoodListBean> list = GsonUtil.mapListToBeanList(results,RequestFoodListBean.class);
                        LogUtils.e("******" + list);

                        requestFoodListBeanList.addAll(list);
                        for (RequestFoodListBean requestFoodListBean : requestFoodListBeanList) {
                            for (FoodBean foodBean : requestFoodListBean.getCaiPList()) {
                                foodBean.setType(requestFoodListBean.getCatalogName());
                            }
                        }
                        firstFragment.setData(requestFoodListBeanList);
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
//                        if (tBaseReponse.getCode()==500){
                        ToastUtils.showToast(tBaseReponse.getMessage());
                        AppConfig.putString("token", "");
                        ARouter.getInstance().build("/app/login").navigation();
//                        }
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {

                    }
                });
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case CAR_ACTION:
                    FoodBean foodBean = (FoodBean) intent.getSerializableExtra("foodbean");
                    FoodBean fb = foodBean;
                    int p = intent.getIntExtra("position", -1);
                    if (p >= 0 && p < firstFragment.getFoodAdapter().getItemCount()) {
                        fb = firstFragment.getFoodAdapter().getItem(p);
                        fb.setSelectCount(foodBean.getSelectCount());
                        firstFragment.getFoodAdapter().setData(p, fb);
                    } else {
                        for (int i = 0; i < firstFragment.getFoodAdapter().getItemCount(); i++) {
                            fb = firstFragment.getFoodAdapter().getItem(i);
                            if (fb.getId() == foodBean.getId()) {
                                fb.setSelectCount(foodBean.getSelectCount());
                                firstFragment.getFoodAdapter().setData(i, fb);
                                break;
                            }
                        }
                    }
                    dealCar(fb);
                    break;
                case CLEARCAR_ACTION:
                    clearCar();
                    break;
            }
            if (CAR_ACTION.equals(intent.getAction())) {

            }
        }
    };

    private void initViews() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initViewpager();
        initShopCar();
    }

    private void initShopCar() {
        behavior = BottomSheetBehavior.from(findViewById(R.id.car_container));
        View blackView = findViewById(R.id.blackview);
        shopCarView.setBehavior(behavior, blackView);
        RecyclerView carRecView = (RecyclerView) findViewById(R.id.car_recyclerview);
//		carRecView.setNestedScrollingEnabled(false);
        carRecView.setLayoutManager(new LinearLayoutManager(mContext));
        ((DefaultItemAnimator) carRecView.getItemAnimator()).setSupportsChangeAnimations(false);
        carAdapter = new CarAdapter(new ArrayList<FoodBean>(), this);
        carAdapter.bindToRecyclerView(carRecView);
    }

    private void initViewpager() {
        scroll_container = findViewById(R.id.scroll_container);
        ScrollIndicatorView mSv = (ScrollIndicatorView) findViewById(R.id.indicator);
        ColorBar colorBar = new ColorBar(mContext, ContextCompat.getColor(mContext, R.color.dicator_line_blue), 6,
                ScrollBar.Gravity.BOTTOM);
        colorBar.setWidth(ViewUtils.dip2px(mContext, 30));
        mSv.setScrollBar(colorBar);
        mSv.setSplitAuto(false);
        mSv.setOnTransitionListener(new OnTransitionTextListener().setColor(ContextCompat.getColor(mContext, R.color.dicator_line_blue),
                ContextCompat.getColor(mContext, R.color.black)));
        ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
        IndicatorViewPager indicatorViewPager = new IndicatorViewPager(mSv, mViewPager);
        firstFragment = new FirstFragment();
        firstFragment.setCanOrder(isCanOrder);
        ViewpagerAdapter myAdapter = new ViewpagerAdapter(getSupportFragmentManager());
        indicatorViewPager.setAdapter(myAdapter);
    }

    private class ViewpagerAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter {
        private LayoutInflater inflater;
        private int padding;
//        private String[] tabs = new String[]{"商品", "评价"};
        private String[] tabs = new String[]{"商品"};
        ViewpagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
            inflater = LayoutInflater.from(mContext);
            padding = ViewUtils.dip2px(mContext, 20);
        }

        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            convertView = inflater.inflate(R.layout.item_textview, container, false);
            TextView textView = (TextView) convertView;
            textView.setText(tabs[position]); //名称
            textView.setPadding(padding, 0, padding, 0);
            return convertView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {
            switch (position) {
                case 0:
                    return firstFragment;
            }
            return new SecondFragment();
        }
    }

    @Override
    public void onAddClick(View view, FoodBean fb) {
        dealCar(fb);
        ViewUtils.addTvAnim(view, shopCarView.carLoc, mContext, rootview);
    }


    @Override
    public void onSubClick(FoodBean fb) {
        dealCar(fb);
    }

    private void dealCar(FoodBean foodBean) {
        HashMap<String, Long> typeSelect = new HashMap<>();//更新左侧类别badge用
        BigDecimal amount = new BigDecimal(0.0);
        int total = 0;
        boolean hasFood = false;
        if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            firstFragment.getFoodAdapter().notifyDataSetChanged();
        }
        List<FoodBean> flist = carAdapter.getData();
        int p = -1;
        for (int i = 0; i < flist.size(); i++) {
            FoodBean fb = flist.get(i);
            if (fb.getId() == foodBean.getId()) {
                fb = foodBean;
                hasFood = true;
                if (foodBean.getSelectCount() == 0) {
                    p = i;
                } else {
                    carAdapter.setData(i, foodBean);
                }
            }
            total += fb.getSelectCount();
            if (typeSelect.containsKey(fb.getType())) {
                typeSelect.put(fb.getType(), typeSelect.get(fb.getType()) + fb.getSelectCount());
            } else {
                typeSelect.put(fb.getType(), fb.getSelectCount());
            }
            amount = amount.add(fb.getPrice().multiply(BigDecimal.valueOf(fb.getSelectCount())));
        }
        if (p >= 0) {
            carAdapter.remove(p);
        } else if (!hasFood && foodBean.getSelectCount() > 0) {
            carAdapter.addData(foodBean);
            if (typeSelect.containsKey(foodBean.getType())) {
                typeSelect.put(foodBean.getType(), typeSelect.get(foodBean.getType()) + foodBean.getSelectCount());
            } else {
                typeSelect.put(foodBean.getType(), foodBean.getSelectCount());
            }
            amount = amount.add(foodBean.getPrice().multiply(BigDecimal.valueOf(foodBean.getSelectCount())));
            total += foodBean.getSelectCount();
        }
        shopCarView.showBadge(total);
        firstFragment.getTypeAdapter().updateBadge(typeSelect);
        shopCarView.updateAmount(amount);
    }

    public void expendCut(View view) {
        float cty = scroll_container.getTranslationY();
        if (!ViewUtils.isFastClick()) {
            ViewAnimator.animate(scroll_container)
                    .translationY(cty, cty == 0 ? AppBarBehavior.cutExpHeight : 0)
                    .decelerate()
                    .duration(100)
                    .start();
        }
    }

    public void clearCar(View view) {
        ViewUtils.showClearCar(mContext, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                clearCar();
            }
        });
    }

    private void clearCar() {
        List<FoodBean> flist = carAdapter.getData();
        for (int i = 0; i < flist.size(); i++) {
            FoodBean fb = flist.get(i);
            fb.setSelectCount(0);
        }
        carAdapter.setNewData(new ArrayList<FoodBean>());
        firstFragment.getFoodAdapter().notifyDataSetChanged();
        shopCarView.showBadge(0);
        firstFragment.getTypeAdapter().updateBadge(new HashMap<String, Long>());
        shopCarView.updateAmount(new BigDecimal(0.0));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    public void toShopDetail(View view) {
        firstFragment.getFoodAdapter().notifyItemChanged(0);
    }

    public void goAccount(View view) {
        if (shopCarView.isCanClick()) {
            //点击结算
            List<FoodBean> foodBeans = carAdapter.getData();
            ARouter.getInstance().build("/app/OrderedActivity")
                    .withString("restaurant",GsonUtil.objectToGson(restaurant))
                    .withString("foods",GsonUtil.listToGson(foodBeans)).navigation();
        }
    }

//    @Override
//    public void finish() {
//        super.finish();
//        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
//    }
}
